package com.java.hohenheim.springplatform.web.security.authentication;

import com.java.hohenheim.springplatform.db.entity.AccountEntity;
import com.java.hohenheim.springplatform.define.ResultCodes;
import com.java.hohenheim.springplatform.exception.PlatformException;
import com.java.hohenheim.springplatform.web.jwt.TokenCheckResult;
import com.java.hohenheim.springplatform.web.jwt.UserToken;
import com.java.hohenheim.springplatform.web.jwt.UserTokenUtils;

import com.java.hohenheim.springplatform.web.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author LiaoJian、Hohenheim
 * @description 用户Token处理领域
 */
@Component
@Slf4j
public class UserAuthenticationRealm extends AuthenticatingRealm {
    @Autowired
    private UserTokenUtils mUserTokenUtils;
    @Autowired
    private AccountService mAccountService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UserAuthentication;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getPrincipal();

        //校验Token
        TokenCheckResult<UserToken> checkResult = mUserTokenUtils.verify(token);
        if(!checkResult.getResult().equals(ResultCodes.RETURN_SUCCESS)) {
            throw new PlatformException(checkResult.getResult());
        }

        //查询是否存在该用户
        UserToken userToken = checkResult.getJwtToken();
        AccountEntity account = mAccountService.getAccountInfo(userToken.getUserId());
        if(null == account) {
            throw new PlatformException(ResultCodes.USER_DOES_NOT_EXIST);
        }

        return new SimpleAuthenticationInfo(userToken, token, getName());
    }
}